const mongoose = require("mongoose")
// 连接mongodb服务器
const db = mongoose.createConnection("mongodb://localhost:27017/mycol", {useNewUrlParser: true})
// 用原生es6的promise取代mongoose自实现的promise
mongoose.Promise = global.Promise
// 在操作数据库之前，使用Schema设置每个字段的类型
db.on("error", console.log.bind(console, "连接数据库失败"))
db.on("open", () => {
  console.log("连接数据库成功")
})
// 连接成功---> 操作数据 ---> 设置Schema
const Schema = mongoose.Schema

// 专门操作JavaScript集合
const JavaScriptSchema = new Schema({
  name: String,
  age: Number,
  sex: {
    type: String,
    default: "🚹"
  }
}, {
  versionKey: false
})

const JavaScript = db.model("javascript", JavaScriptSchema, "colname")

const data1 = {
  name: "小强",
  age: 27,
  sex: "男"
}
const data2 = {
  name: "小红",
  age: 20,
  sex: "女"
}

const d1 = new JavaScript(data1)
d1
  .save()
  .then(res => {
    console.log(res)
  })
  .catch(err => {
    console.log(err)
  })


